package com.atguigu.base.synvslock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SyncVSLock {
    private final Lock L = new ReentrantLock();
    public synchronized void m1(){
        System.out.println(Thread.currentThread().getName()+"\t"+"come in");
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public  void m2(){
        if(L.tryLock()){
            try{
                System.out.println(Thread.currentThread().getName()+"\t"+"come in");
                try{
                    TimeUnit.SECONDS.sleep(2);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }finally {
                L.unlock();
            }
        }else{
            System.out.println(Thread.currentThread().getName()+ "抢夺失败");
        }
    }
    public   void m3(){
        try {
            if (L.tryLock(2L, TimeUnit.SECONDS)) {
                try {
                    System.out.println(Thread.currentThread().getName() + "\t" + "come in");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } finally {
                    L.unlock();
                }
            } else {
                System.out.println(Thread.currentThread().getName() + "\t" + "抢锁失败");
            }
        }catch(Exception e){
            e.printStackTrace();
        }

    }
}